package noten;

import java.io.Serializable;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import database.AppDatabase;
import database.NotenDatabaseService;
import de.app.badresden.R;

public class NotenActivity extends Activity implements OnCancelListener {

	private ProgressDialog progressdialog;
	private NotenDatabaseService dbService;
	private boolean internet;
	
	public void onCreate(Bundle icicle) {

		super.onCreate(icicle);

		dbService = new NotenDatabaseService(
				new AppDatabase(getApplicationContext()).getWritableDatabase());

		internet = getIntent().getExtras().getBoolean("HasInternet");
					
		if (internet) progressdialog = ProgressDialog.show(NotenActivity.this,
				getString(R.string.progressdialog_title),
				getString(R.string.progressdialog_noten), true, true, this);
		else
			progressdialog = ProgressDialog.show(NotenActivity.this,
					getString(R.string.progressdialog_title),
					getString(R.string.progressdialog_database), true, true, this);

		String cookievalue = getIntent().getExtras().getString("cookievalue");
		String url = getString(R.string.url_noten);
		startNotenimport(cookievalue, internet, url);
	}

	private void startNotenimport(final String cookievalue, final boolean internet, final String url) {

		Thread notenimportThread = new Thread() {

			@Override
			public void run() {

				try {
					synchronized (this) {
						List<Modul> notenuebersicht;

						if (internet) {
							notenuebersicht = new Notenimport(cookievalue, url).getNoten();
						}
						else {
							notenuebersicht = dbService.getNoten();
							Thread.sleep(5000);
						}

						Bundle bundle = new Bundle();
						bundle.putSerializable("notenuebersicht",
								(Serializable) notenuebersicht);

						Message msg = new Message();
						msg.setData(bundle);
						updateHandler.sendMessage(msg);
					}
				}
				catch (InterruptedException ex) {}
				catch (Exception e) {
					Log.d("badresden app", e.toString());
				}
			}
		};
		notenimportThread.start();
	}

	private Handler updateHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			super.handleMessage(msg);
			Bundle bundle = msg.getData();
			List<Modul> notenuebersicht = (List<Modul>) bundle
					.getSerializable("notenuebersicht");
			
			setContentView(R.layout.noten_layout);

			SharedPreferences preferences = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			if (preferences.getBoolean("save_data", false) && internet) {
				dbService.insertNoten(notenuebersicht);
			}

			progressdialog.dismiss();
			showNotenInView(notenuebersicht);
		}
	};

	private void showNotenInView(List<Modul> notenuebersicht) {

		Modul durchschnitt = new Modul();
		durchschnitt.setBezeichnung(getString(R.string.noten_durchschnitt));
		durchschnitt.setBewertung(new Notendurchschnitt(notenuebersicht)
				.berechneDurchschnitt());
		notenuebersicht.add(durchschnitt);

		ListView listView = (ListView)findViewById(R.id.noten_listview);
		ArrayAdapter<Modul> listViewAdapter = new NotenArrayAdapter(this, notenuebersicht);
		listView.setAdapter(listViewAdapter);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		dbService.close();
	}

	@Override
	public void onCancel(DialogInterface dialog) {
		// TODO Auto-generated method stub
		progressdialog.dismiss();
		finish();
	}
}
